package mk.jug.academy.service;


import javax.persistence.NoResultException;

import mk.jug.academy.dao.SupporterDAO;
import mk.jug.academy.exception.BusinessException;
import mk.jug.academy.model.Page;
import mk.jug.academy.model.Supporter;
import mk.jug.academy.model.SupporterStatus;
import mk.jug.academy.preconditions.ErrorCodes;
import mk.jug.academy.preconditions.PreconditionExceptions;
import mk.jug.academy.util.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/**
 * Provides the business logic implementation for {@link SupporterService}. 
 *
 * @author Ice.Penov
 */
@Service
public class SupporterServiceImpl implements SupporterService {

	@Autowired private SupporterDAO supporterDAO;
	
	@Override
	public void signUpSupporter(Supporter supporter) {
		Assert.notNull(supporter.getFirstName(), PreconditionExceptions.MISSING_FIRST_NAME);
		Assert.notNull(supporter.getLastName(), PreconditionExceptions.MISSING_LAST_NAME);
		Assert.notNull(supporter.getEmail(), PreconditionExceptions.MISSING_EMAIL);
		if (!exists(supporter.getEmail())) {
			supporter.setStatus(SupporterStatus.SIGNED_UP);
			supporterDAO.save(supporter);
		} else {
			throw new BusinessException(ErrorCodes.ERROR_EMAIL_EXISTS);
		}
	}

	@Override
	public Page<Supporter> listSignedUp(int pageNumber, int itemsPerPage) {
		return supporterDAO.findByStatus(SupporterStatus.SIGNED_UP, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}
	
	@Override
	public Page<Supporter> listActive(int pageNumber, int itemsPerPage) {
		return supporterDAO.findByStatus(SupporterStatus.ACTIVE, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}
	
	@Override
	public Page<Supporter> listDeleted(int pageNumber, int itemsPerPage) {
		return supporterDAO.findByStatus(SupporterStatus.DELETED, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}
	
	@Override
	public void activateSupporter(Supporter supporter) {
		supporter.setStatus(SupporterStatus.ACTIVE);
		supporterDAO.save(supporter);
	}
	
	@Override
	public void deleteSupporter(Supporter supporter) {
		supporter.setStatus(SupporterStatus.DELETED);
		supporterDAO.save(supporter);
	}

	@Override
	public boolean exists(String email) {
		try {
			supporterDAO.findAnyByEmail(email);
		} catch (NoResultException e) {
			return false;
		}
		return true;
	}
	
	@Override
	public Supporter findByEmail(String email) {
		Supporter s = null;
		try {
			s = supporterDAO.findActiveByEmail(email);
		} catch (NoResultException e) {
			;
		}
		return s;
		
	}
	
	@Override
	public Supporter load(Long id) {
		return supporterDAO.find(Supporter.class, id);
	}
	
}